package com.gzpi.hwgggh.utils;

import com.gzpi.hwgggh.entity.DWTP;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @date : 2021-02-03 09:33
 **/
public class CommonTools {


    public static void getMapData(Map<String,Object> map, String condition, String number){
        if (map.containsKey(condition)){
            String mapval = (String) map.get(condition); //原拼接编号
            String orid = mapval;
            String one = "0"; //最后一个编号
            int i1 = mapval.lastIndexOf("/");//获取最后一个/下标
            int i2 = mapval.lastIndexOf("-");//获取最后一个-下标
            Integer intid = Integer.valueOf(number);
            if (i2<i1){//最后一个出现的是 /
                one = mapval.substring(i1+1);//获取最后一个编号
                orid = mapval;
            }else if (i1<i2){//最后一个出现的是 -
                one = mapval.substring(i2+1);//获取最后一个编号
                orid = mapval.substring(0,i2);//获取第一个编号
            }else{
                one = mapval;
            }
            Integer intone = Integer.valueOf(one);
            if (intone<intid && intone+1==intid){//判断最后一个最后一个编号是否小于新编号 （最后一个编号+1是否等于新编号）
                map.put(condition,orid+"-"+number);
            }else if (intone<intid && intone+1!=intid){//判断最后一个最后一个编号是否小于新编号 （最后一个编号+1是否不等于新编号）
                orid = mapval;
                map.put(condition,orid+"/"+number);
            }
        }else {
            map.put(condition,number);
        }
    }

    public static String mapSort(Map<String,Object> map){
        String data = "";
        if (map!=null&&!map.isEmpty()){
            //自定义比较器
            Comparator<Map.Entry<String, Object>> valCmp = new Comparator<Map.Entry<String,Object>>() {
                @Override
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    Integer val1 = getVal(o1.getValue().toString());
                    Integer val2 = getVal(o2.getValue().toString());
                    return val1-val2;  // 降序排序，如果想升序就反过来
                }
            };
            //将map转成List，map的一组key，value对应list一个存储空间
            List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String,Object>>(map.entrySet()); //传入maps实体
            Collections.sort(list,valCmp); // 注意此处Collections 是java.util包下面的,传入List和自定义的valCmp比较器


            for (Map.Entry<String, Object> entry : list) {
                data += entry.getValue().toString()+":"+entry.getKey()+"；";
            }

        }
        return data;
    }


    private static Integer getVal(String mapval){
        int i1 = mapval.indexOf("/");//获取最后一个/下标
        int i2 = mapval.indexOf("-");//获取最后一个-下标
        String i3 = "0";
        if (i1!=-1 && i2!=-1){
            if (i2>i1){//第一个出现的是 /
                i3 = mapval.substring(0,i1);
            }else if (i1>i2){//第一个一个出现的是 -
                i3 = mapval.substring(0,i2);
            }
        }else{
            if (i1!=-1){
                i3 = mapval.substring(0,i1);
            }else if (i2!=-1){
                i3 = mapval.substring(0,i2);
            }else{
                i3 = mapval;
            }
        }
        return Integer.valueOf(i3);
    }

    public static  List<Map<String,Object>> mergeInformation(List<Map> maps){
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> list = new ArrayList<>();

        for (Map map1 : maps) {
            if (map1.containsKey("DWBH")){
                String dwbh = (String) map1.get("DWBH");
                if (!map.containsKey(dwbh)){
                    map.put(dwbh,map1);
                }else{
                    Map<String,Object> map2 = (Map<String, Object>) map.get(dwbh);

                    if (map1.containsKey("COUNT")){
                        Integer count =  Integer.valueOf(map1.get("COUNT").toString());
                        Integer count1 = Integer.valueOf(map2.get("COUNT").toString());
                        map2.put("COUNT",count+count1);
                    }
                    if (map1.containsKey("BLCOUNT")){
                        Integer count = Integer.valueOf(map1.get("BLCOUNT").toString());
                        Integer count1 = Integer.valueOf(map2.get("BLCOUNT").toString());
                        map2.put("BLCOUNT",count+count1);
                    }
                    if (map1.containsKey("TDCOUNT")){
                        Integer count = Integer.valueOf(map1.get("TDCOUNT").toString());
                        Integer count1 = Integer.valueOf(map2.get("TDCOUNT").toString());
                        map2.put("TDCOUNT",count+count1);
                    }
                    if (map1.containsKey("XZCOUNT")){
                        Integer count = Integer.valueOf(map1.get("XZCOUNT").toString());
                        Integer count1 = Integer.valueOf(map2.get("XZCOUNT").toString());
                        map2.put("XZCOUNT",count+count1);
                    }
                    if (map1.containsKey("CCCOUNT")){
                        Integer count = Integer.valueOf(map1.get("CCCOUNT").toString());
                        Integer count1 = Integer.valueOf(map2.get("CCCOUNT").toString());
                        map2.put("CCCOUNT",count+count1);
                    }

                }
            }
        }


        Map<String, Object> resultMap = sortMapByKey(map);    //按Key进行排序

        for (String key : resultMap.keySet()) {
            list.add((Map<String, Object>) map.get(key));
        }

        return list;
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }

    /**
     *  拆分list集合
     * @param targe  将要被拆分的list
     * @param targeSplitSize  将要被拆分的每个list的个数
     * @return
     */
    public static List createList(List<Map<String,Object>> targe,int targeSplitSize){
        List resultList = new ArrayList<List<Map<String,Object>>>() ;
        //先求每组平均分多少个,如果不够分补足，最后一个少分
        int avgSize = targe.size()%targeSplitSize==0?targe.size()/targeSplitSize:targe.size()/targeSplitSize+1;
        //求出最后一组的个数
        int lastArraySize = targeSplitSize - (avgSize*(targeSplitSize) - targe.size());
        int k = 0;  //取出list中元素的计数器
        for(int i=0; i<avgSize; i++){
            List list = new ArrayList<Map<String,Object>>();
            //如果不是最后一组则按照平均大小拆分目标list
            if(i !=(avgSize-1)){
                for(int j=0; j<targeSplitSize; j++){
                    Map<String, Object> map = targe.get(k);
                    list.add(map);
                    k++;
                }
            }else{
                for(int j=0; j<lastArraySize; j++){
                    Map<String, Object> map = targe.get(k);
                    list.add(map);
                    k++;
                }
            }
            resultList.add(list);
        }
        return resultList;
    }

    public static String getCurrentTime(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public static String getCurrentTimeMillis() {
        try {
            Thread.sleep(10); //1000 毫秒，也就是1秒.
            return String.valueOf(System.currentTimeMillis());
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        return String.valueOf(System.currentTimeMillis());
    }

    public static void uploadFile(MultipartFile file, DWTP dwtp, String dwxid, HttpServletRequest request) throws Exception{
        String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String start = fileName.substring(0, fileName.indexOf("_") + 1);
        String newFileName = start+dwxid;
        //根据已有图片名覆盖原文件，无已有图片名则用新文件名
        switch (start) {
            case "GHT_":
                if (StringUtils.isNotBlank(dwtp.getGHT()))
                    newFileName = dwtp.getGHT().substring(dwtp.getGHT().lastIndexOf("/")+1, dwtp.getGHT().lastIndexOf("."));
                break;
            case "GHTR_":
                if (StringUtils.isNotBlank(dwtp.getGHTR()))
                    newFileName = dwtp.getGHTR().substring(dwtp.getGHTR().lastIndexOf("/")+1, dwtp.getGHTR().lastIndexOf("."));
                break;
            case "GHTY_":
                if (StringUtils.isNotBlank(dwtp.getGHTY()))
                    newFileName = dwtp.getGHTY().substring(dwtp.getGHTY().lastIndexOf("/")+1, dwtp.getGHTY().lastIndexOf("."));
                break;
            case "QWT_":
                if (StringUtils.isNotBlank(dwtp.getQWT()))
                    newFileName = dwtp.getQWT().substring(dwtp.getQWT().lastIndexOf("/")+1, dwtp.getQWT().lastIndexOf("."));
                break;
            case "XZT_":
                if (StringUtils.isNotBlank(dwtp.getXZT()))
                    newFileName = dwtp.getXZT().substring(dwtp.getXZT().lastIndexOf("/")+1, dwtp.getXZT().lastIndexOf("."));
                break;
            case "CCT_":
                if (StringUtils.isNotBlank(dwtp.getCCT()))
                    newFileName = dwtp.getCCT().substring(dwtp.getCCT().lastIndexOf("/")+1, dwtp.getCCT().lastIndexOf("."));
                break;
        }
        //保存文件
        FileResult fileResult = FileUtil.saveFileToPath(request, file, HwggConstants.SAVE_PATH + dwxid, HwggConstants.MAPPING_PATH + dwxid,newFileName);
        if (!fileResult.isFlag()){
            throw  new RuntimeException("文件保存失败");
        }
        //根据文件名前缀保存到对应字段
        switch (start){
            case "GHT_":
                dwtp.setGHT(fileResult.getHttpUrl());
                break;
            case "GHTR_":
                dwtp.setGHTR(fileResult.getHttpUrl());
                break;
            case "GHTY_":
                dwtp.setGHTY(fileResult.getHttpUrl());
                break;
            case "QWT_":
                dwtp.setQWT(fileResult.getHttpUrl());
                break;
            case "XZT_":
                dwtp.setXZT(fileResult.getHttpUrl());
                break;
            case "CCT_":
                dwtp.setCCT(fileResult.getHttpUrl());
                break;
        }
    }
}




class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }
}